import 'package:dio/dio.dart';
import 'package:my_app/common/http/api_response.dart';
import 'package:my_app/common/http/app_exceptions.dart';
import 'package:my_app/model/ModelBase.dart';

typedef invokeFunction = Future<dynamic> Function();

typedef creatorFunction = dynamic Function(dynamic);

class DaoBase {
  Future<ApiResponse> invoke<T>(invokeFunction future, {creatorFunction creator}) async {
    try {
      final response = await future();
      if (response["code"] == 0) {
        if (creator != null) {
          var data = creator(response["data"]);
          return ApiResponse<T>.completed(data);
        }
        return ApiResponse<T>.completed(response["data"]);
      } else {
        return ApiResponse<T>.error(BadRequestException(response["code"], response["msg"]));
      }
    } on DioError catch (e) {
      return ApiResponse<T>.error(e.error);
    }
  }
}
